<template>
  <Card
    class="card-wrap h-full relative overflow-hidden"
    :body-style="{ padding: 0, margin: 0 }"
    :style="styles"
  >
    <Tree
      :selectedKeys="selectedKeys"
      v-model:expanded-keys="expandedKeys"
      :tree-data="treeData"
      :field-names="fileNames"
      default-expand-all
      @select="onSelect"
      style="width: 280px"
    />
    <div class="close" @click="onClose">
      <CaretRightOutlined v-if="isClose" />
      <CaretLeftOutlined v-else />
    </div>
  </Card>
</template>

<script setup lang="tsx">
import { CSSProperties, PropType, computed, ref } from 'vue';
import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons-vue';
import { Card, Tree, TreeProps } from 'ant-design-vue';
import {
  getTreeFirstChildrenValue,
  noop,
  treeToArray,
  treeToEnum,
} from '@/utils/utils';
import { fetchDepartmentApi } from '@/api/system';

defineOptions({
  name: 'StationTree',
});

const props = defineProps({
  search: {
    type: Function as PropType<(params: Record<string, any>) => void>,
    default: noop,
  },
  deptId: {
    type: Number,
  },
});

const expandedKeys = ref<string[]>([]);
const treeEnum = ref<Record<string, any>>({});
const treeData = ref([]);
const fileNames: TreeProps['fieldNames'] = {
  title: 'label',
  key: 'id',
  children: 'children',
};

const selectedKeys = computed(() => [props.deptId]);

const onSelect: TreeProps['onSelect'] = (_, item) => {
  const params = {
    deptId: item.node.id,
  };
  props.search(params);
};

const isClose = ref<boolean>(false);
const styles = computed<CSSProperties>(() =>
  isClose.value
    ? {
        width: '18px',
        border: 0,
      }
    : { width: '280px', paddingRight: '20px' },
);
const onClose = () => {
  isClose.value = !isClose.value;
};

const initData = () => {
  fetchDepartmentApi().then((res) => {
    treeData.value = res.data as any;
    expandedKeys.value = getTreeFirstChildrenValue(res.data, 'id');
    treeEnum.value = treeToEnum(res.data, {
      label: 'label',
      value: 'id',
    });
  });
};

initData();
</script>
